<?php

/*
	Title: pagepart

	About: Author
		Rich Joslin

	About: License
		<http://communit.as/docs/license>

	Function: smarty_function_pagepart
		Prints script tags based on a space-delimited list of URLs passed in.
		When setting the urls array, any tabs or carriage returns are stripped out and replaced with spaces so the split will work.
		So format it any way you want (theoretically).

	Arguments:
		$params - An array of variables.
		&$smarty - TBD

	Params:
		TBD

	Returns:
		A string containing one or more script tags.

	Examples:
		(begin example)
			<!-- as used in a Smarty view template -->
			{pagepart id=3 locale=$locale}
			{pagepart id=45 locale="en-US"}
		(end example)
*/
function smarty_function_pagepart($params, &$smarty) {
	$output = "";
	$short_name = $params['short_name'];
	$locale = $params['locale'];
	$content_table = new PagepartsViewContent();
	
	$select = $content_table->select();
	
	if( isset($params['part']) ){
		$select->where("short_name = ?", $params['part']);
	} elseif( isset($params['part_id']) ){
		$select->where("part_id = ?", $params['part_id']);
	} elseif( isset($params['id']) ){
		$select->where("part_id = ?", $params['id']);
	} else {
		return;
	}
	
	if( isset($params['page']) ){
		$select->where("page_short_name = ?", $params['page']);
	}
	
	if( isset($params['locale']) ){
		$select->where("locale = ?", $params['locale']);
	}
	
	$parts = $content_table->fetchAllArray(
		$select->where("active = '1'")
		->where("publish_on < '".date(DB_DATETIME_FORMAT)."'")
		->order("version desc")
		->limit("1")
	);
	
	if( $parts && is_array($parts) && count($parts)==1 && isset($parts[0]['metadata']) ){
		$output = @unserialize($parts[0]['metadata']);
	} elseif( $parts && is_array($parts) && count($parts)>1 ){
		// Support for older versions at the template level would go here
		return;
	} else {
		return;
	}

	if( isset($params['assign']) ){
		$smarty->assign($params['assign'], $output);
		return;
	} else {
		return $output;
	}
}
